package com.hutgin2.dao.hibernate;

import com.hutgin2.dao.search.ExampleOptions;
import com.hutgin2.dao.search.ISearch;
import com.hutgin2.dao.search.SearchResult;
import com.hutgin2.dao.search.hibernate.EntityNameMetadataUtil;
import com.hutgin2.dao.search.hibernate.EntityNameSearchProcessor;
import org.hibernate.*;
import org.hibernate.criterion.Restrictions;

import java.io.Serializable;
import java.util.List;

public class EntityNameBaseDAO {

    private EntityNameSearchProcessor searchProcessor;

    private SessionFactory sessionFactory;

    private EntityNameMetadataUtil metadataUtil;

    public EntityNameBaseDAO(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
        searchProcessor = EntityNameSearchProcessor.getInstanceForSessionFactory(sessionFactory);
        metadataUtil = EntityNameMetadataUtil.getInstanceForSessionFactory(sessionFactory);
    }

    protected SessionFactory getSessionFactory() {
        return sessionFactory;
    }

    /**
     * Get the current Hibernate session
     */
    protected Session getSession() {
        return sessionFactory.getCurrentSession();
    }

    /**
     * Get the instance of EntityNameMetadataUtil associated with the session
     * factory
     */
    protected EntityNameMetadataUtil getMetadataUtil() {
        return metadataUtil;
    }

    /**
     * Get the instance of EJBSearchProcessor associated with the session
     * factory
     */
    protected EntityNameSearchProcessor getSearchProcessor() {
        return searchProcessor;
    }

    /**
     * <p/>
     * Persist the given transient instance and add it to the datastore, first
     * assigning a generated identifier. (Or using the current value of the
     * identifier property if the assigned generator is used.) This operation
     * cascades to associated instances if the association is mapped with
     * cascade="save-update".
     * <p/>
     * <p/>
     * This is different from <code>persist()</code> in that it does guarantee
     * that the object will be assigned an identifier immediately. With
     * <code>save()</code> a call is made to the datastore immediately if the id
     * is generated by the datastore so that the id can be determined. With
     * <code>persist</code> this call may not occur until flush time.
     *
     * @return The id of the newly saved entity.
     */
    protected Serializable _save(String entityName, Object entity) {
        return getSession().save(entityName, entity);
    }

    /**
     * Persist the given transient instances and add them to the datastore,
     * first assigning a generated identifier. (Or using the current value of
     * the identifier property if the assigned generator is used.) This
     * operation cascades to associated instances if the association is mapped
     * with cascade="save-update".
     */
    protected void _save(String entityName, Object... entities) {
        for (Object entity : entities) {
            _save(entityName, entity);
        }
    }

    /**
     * <p/>
     * Calls Hibernate's <code>saveOrUpdate()</code>, which behaves as follows:
     * <p/>
     * <p/>
     * Either <code>save()</code> or <code>update()</code> based on the
     * following rules
     * <ul>
     * <li>if the object is already persistent in this session, do nothing
     * <li>
     * if another object associated with the session has the same identifier,
     * throw an exception
     * <li>if the object has no identifier property, save() it
     * <li>if the object's identifier has the value assigned to a newly
     * instantiated object, save() it
     * <li>if the object is versioned (by a &lt;version&gt; or
     * &lt;timestamp&gt;), and the version property value is the same value
     * assigned to a newly instantiated object, save() it
     * <li>otherwise update() the object
     * </ul>
     */
    protected void _saveOrUpdate(String entityName, Object entity) {
        getSession().saveOrUpdate(entityName, entity);
    }

    /**
     * <p/>
     * If an entity already exists in the datastore with the same id, call
     * _update and return false (not new). If no such entity exists in the
     * datastore, call _save() and return true (new)
     *
     * @return <code>true</code> if _save(); <code>false</code> if _update().
     */
    protected boolean _saveOrUpdateIsNew(String entityName, Object entity) {
        if (entity == null)
            throw new IllegalArgumentException("attempt to saveOrUpdate with null entity");

        Serializable id = getMetadataUtil().getId(entityName, entity);
        if (getSession().contains(entity))
            return false;

        if (id == null || (new Long(0)).equals(id) || !_exists(entityName, entity)) {
            _save(entityName, entity);
            return true;
        } else {
            _update(entityName, entity);
            return false;
        }
    }

    /**
     * Either <code>save()</code> or <code>update()</code> each entity,
     * depending on whether or not an entity with the same id already exists in
     * the datastore.
     *
     * @return an boolean array corresponding to to the input list of entities.
     *         Each element is <code>true</code> if the corresponding entity was
     *         <code>_save()</code>d or <code>false</code> if it was
     *         <code>_update()</code>d.
     */
    protected boolean[] _saveOrUpdateIsNew(String entityName, Object... entities) {
        boolean[] res = new boolean[entities.length];

        // if an entity is contained in the session, it exists; if it has no id,
        // it does not exist
        for (int i = 0; i < entities.length; i++) {
            if (entities[i] == null) {
                throw new IllegalArgumentException("attempt to saveOrUpdate with null entity");
            }
            res[i] = _saveOrUpdateIsNew(entityName, entities[i]);
        }


        return res;
    }

    /**
     * <p/>
     * Make a transient instance persistent and add it to the datastore. This
     * operation cascades to associated instances if the association is mapped
     * with cascade="persist". Throws an error if the entity already exists.
     * <p/>
     * <p/>
     * This is different from <code>save()</code> in that it does not guarantee
     * that the object will be assigned an identifier immediately. With
     * <code>save()</code> a call is made to the datastore immediately if the id
     * is generated by the datastore so that the id can be determined. With
     * <code>persist</code> this call may not occur until flush time.
     */
    protected void _persist(Object... entities) {
        for (Object entity : entities) {
            getSession().persist(entity);
        }
    }

    /**
     * Remove the entity of the specified class with the specified id from the
     * datastore.
     *
     * @return <code>true</code> if the object is found in the datastore and
     *         deleted, <code>false</code> if the item is not found.
     */
    protected boolean _deleteById(String entityName, Serializable id) {
        if (id != null) {
            Object entity = getSession().get(entityName, id);
            if (entity != null) {
                getSession().delete(entityName, entity);
                return true;
            }
        }
        return false;
    }

    /**
     * Remove all the entities of the given type from the datastore that have
     * one of these ids.
     */
    protected void _deleteById(String entityName, Serializable... ids) {
        Criteria c = getSession().createCriteria(entityName);
        c.add(Restrictions.in("id", ids));
        for (Object entity : c.list()) {
            getSession().delete(entityName, entity);
        }
    }

    /**
     * Remove the specified entity from the datastore.
     *
     * @return <code>true</code> if the object is found in the datastore and
     *         removed, <code>false</code> if the item is not found.
     */
    protected boolean _deleteEntity(String entityName, Object entity) {
        if (entity != null) {
            Serializable id = getMetadataUtil().getId(entityName, entity);
            if (id != null) {
                entity = getSession().get(entityName, id);
                if (entity != null) {
                    getSession().delete(entityName, entity);
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * Remove the specified entities from the datastore.
     */
    protected void _deleteEntities(String entityName, Object... entities) {
        for (Object entity : entities) {
            if (entity != null)
                getSession().delete(entityName, entity);
        }
    }

    /**
     * Return the persistent instance of the given entity class with the given
     * identifier, or null if there is no such persistent instance.
     * <code>get()</code> always hits the database immediately.
     */
    protected <T> T _get(String entityName, Serializable id) {
        return (T) getSession().get(entityName, id);
    }

    /**
     * <p/>
     * Return the all the persistent instances of the given entity class with
     * the given identifiers. An array of entities is returned that matches the
     * same order of the ids listed in the call. For each entity that is not
     * found in the datastore, a null will be inserted in its place in the
     * return array.
     * <p/>
     * <p/>
     * <code>get()</code> always hits the database immediately.
     */
    protected <T> T[] _get(String entityName, Serializable... ids) {
        Criteria c = getSession().createCriteria(entityName);
        c.add(Restrictions.in("id", ids));
        Object[] retVal = new Object[ids.length];

        for (Object entity : c.list()) {
            Serializable id = getMetadataUtil().getId(entityName, entity);
            for (int i = 0; i < ids.length; i++) {
                if (id.equals(ids[i])) {
                    retVal[i] = entity;
                    break;
                }
            }
        }

        return (T[]) retVal;
    }

    /**
     * <p/>
     * Return the persistent instance of the given entity class with the given
     * identifier, assuming that the instance exists. Throw an unrecoverable
     * exception if there is no matching database row.
     * <p/>
     * <p/>
     * If the class is mapped with a proxy, <code>load()</code> just returns an
     * uninitialized proxy and does not actually hit the database until you
     * invoke a method of the proxy. This behaviour is very useful if you wish
     * to create an association to an object without actually loading it from
     * the database. It also allows multiple instances to be loaded as a batch
     * if batch-size is defined for the class mapping.
     */
    protected <T> T _load(String entityName, Serializable id) {
        return (T) getSession().load(entityName, id);
    }

    /**
     * <p/>
     * Return the persistent instance of the given entity class with the given
     * identifier, assuming that the instance exists. Throw an unrecoverable
     * exception if there is no matching database row. An array of entities is
     * returned that matches the same order of the ids listed in the call. For
     * each entity that is not found in the datastore, a null will be inserted
     * in its place in the return array.
     *
     * @see #_load(String, Serializable)
     */
    protected <T> T[] _load(String entityName, Serializable... ids) {
        Object[] retVal = new Object[ids.length];
        for (int i = 0; i < ids.length; i++) {
            if (ids[i] != null)
                retVal[i] = _load(entityName, ids[i]);
        }
        return (T[]) retVal;
    }

    /**
     * Read the persistent state associated with the given identifier into the
     * given transient instance. Throw an unrecoverable exception if there is no
     * matching database row.
     */
    protected void _load(Object transientEntity, Serializable id) {
        getSession().load(transientEntity, id);
    }

    /**
     * Get a list of all the objects of the specified class.
     */
    protected <T> List<T> _all(String entityName) {
        return getSession().createCriteria(entityName).setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY).list();
    }

    /**
     * <p/>
     * Update the persistent instance with the identifier of the given detached
     * instance. If there is a persistent instance with the same identifier, an
     * exception is thrown. This operation cascades to associated instances if
     * the association is mapped with cascade="save-update".
     * <p/>
     * <p/>
     * The difference between <code>update()</code> and <code>merge()</code> is
     * significant: <code>update()</code> will make the given object persistent
     * and throw and error if another object with the same ID is already
     * persistent in the Session. <code>merge()</code> doesn't care if another
     * object is already persistent, but it also doesn't make the given object
     * persistent; it just copies over the values to the datastore.
     */
    protected void _update(String entityName, Object... transientEntities) {
        for (Object entity : transientEntities) {
            getSession().update(entityName, entity);
        }
    }

    /**
     * <p/>
     * Copy the state of the given object onto the persistent object with the
     * same identifier. If there is no persistent instance currently associated
     * with the session, it will be loaded. Return the persistent instance. If
     * the given instance is unsaved, save a copy of and return it as a newly
     * persistent instance. The given instance does not become associated with
     * the session. This operation cascades to associated instances if the
     * association is mapped with cascade="merge".
     * <p/>
     * <p/>
     * The difference between <code>update()</code> and <code>merge()</code> is
     * significant: <code>update()</code> will make the given object persistent
     * and throw and error if another object with the same ID is already
     * persistent in the Session. <code>merge()</code> doesn't care if another
     * object is already persistent, but it also doesn't make the given object
     * persistent; it just copies over the values to the datastore.
     */
    protected <T> T _merge(String entityName, T entity) {
        return (T) getSession().merge(entityName, entity);
    }

    /**
     * Search for objects based on the search parameters in the specified
     * <code>ISearch</code> object.
     *
     * @see com.hutgin2.core.dao.search.ISearch
     */
    protected List _search(ISearch search) {
        if (search == null)
            throw new NullPointerException("Search is null.");
        if (search.getEntityName() == null)
            throw new NullPointerException("Search class is null.");

        return getSearchProcessor().search(getSession(), search);
    }

    /**
     * Same as <code>_search(ISearch)</code> except that it uses the specified
     * search class instead of getting it from the search object. Also, if the search
     * object has a different search class than what is specified, an exception
     * is thrown.
     */
    protected List _search(String entityName, ISearch search) {
        if (search == null)
            throw new NullPointerException("Search is null.");
        if (entityName == null)
            throw new NullPointerException("Search class is null.");
        if (search.getEntityName() != null && !search.getEntityName().equals(entityName))
            throw new IllegalArgumentException("Search class does not match expected type: " + entityName);

        return getSearchProcessor().search(getSession(), entityName, search);
    }

    /**
     * Returns the total number of results that would be returned using the
     * given <code>ISearch</code> if there were no paging or maxResult limits.
     *
     * @see ISearch
     */
    protected int _count(ISearch search) {
        if (search == null)
            throw new NullPointerException("Search is null.");
        if (search.getEntityName() == null)
            throw new NullPointerException("Search class is null.");

        return getSearchProcessor().count(getSession(), search);
    }

    /**
     * Same as <code>_count(ISearch)</code> except that it uses the specified
     * search class instead of getting it from the search object. Also, if the search
     * object has a different search class than what is specified, an exception
     * is thrown.
     */
    protected int _count(String entityName, ISearch search) {
        if (search == null)
            throw new NullPointerException("Search is null.");
        if (entityName == null)
            throw new NullPointerException("Search class is null.");
        if (search.getEntityName() != null && !search.getEntityName().equals(entityName))
            throw new IllegalArgumentException("Search class does not match expected type: " + entityName);

        return getSearchProcessor().count(getSession(), entityName, search);
    }

    /**
     * Returns the number of instances of this class in the datastore.
     */
    protected int _count(String entityName) {
        List counts = getSession().createQuery("select count(_it_) from " + entityName + " _it_").list();
        int sum = 0;
        for (Object count : counts) {
            sum += ((Long) count).intValue();
        }
        return sum;
    }

    /**
     * Returns a <code>SearchResult</code> object that includes the list of
     * results like <code>search()</code> and the total length like
     * <code>searchLength</code>.
     *
     * @see ISearch
     */
    protected SearchResult _searchAndCount(ISearch search) {
        if (search == null)
            throw new NullPointerException("Search is null.");
        if (search.getEntityName() == null)
            throw new NullPointerException("Search class is null.");

        return getSearchProcessor().searchAndCount(getSession(), search);
    }

    /**
     * Same as <code>_searchAndCount(ISearch)</code> except that it uses the specified
     * search class instead of getting it from the search object. Also, if the search
     * object has a different search class than what is specified, an exception
     * is thrown.
     */
    protected SearchResult _searchAndCount(String entityName, ISearch search) {
        if (search == null)
            throw new NullPointerException("Search is null.");
        if (entityName == null)
            throw new NullPointerException("Search class is null.");
        if (search.getEntityName() != null && !search.getEntityName().equals(entityName))
            throw new IllegalArgumentException("Search class does not match expected type: " + entityName);

        return getSearchProcessor().searchAndCount(getSession(), entityName, search);
    }

    /**
     * Search for a single result using the given parameters.
     */
    protected Object _searchUnique(ISearch search) throws NonUniqueResultException {
        if (search == null)
            throw new NullPointerException("Search is null.");
        if (search.getEntityName() == null)
            throw new NullPointerException("Search class is null.");

        return getSearchProcessor().searchUnique(getSession(), search);
    }

    /**
     * Same as <code>_searchUnique(ISearch)</code> except that it uses the specified
     * search class instead of getting it from the search object. Also, if the search
     * object has a different search class than what is specified, an exception
     * is thrown.
     */
    protected Object _searchUnique(String entityName, ISearch search) {
        if (search == null)
            throw new NullPointerException("Search is null.");
        if (entityName == null)
            throw new NullPointerException("Search class is null.");
        if (search.getEntityName() != null && !search.getEntityName().equals(entityName))
            throw new IllegalArgumentException("Search class does not match expected type: " + entityName);

        return getSearchProcessor().searchUnique(getSession(), entityName, search);
    }

    /**
     * Returns true if the object is connected to the current hibernate session.
     */
    protected boolean _sessionContains(String entityName, Object o) {
        return getSession().contains(o);
    }

    /**
     * Flushes changes in the hibernate cache to the datastore.
     */
    protected void _flush() {
        getSession().flush();
    }

    /**
     * Refresh the content of the given entity from the current datastore state.
     */
    protected void _refresh(String entityName, Object... entities) {
        for (Object entity : entities)
            getSession().refresh(entityName, entity);
    }

    protected boolean _exists(String entityName, Object entity) {
        if (getSession().contains(entity))
            return true;
        return _exists(entityName, getMetadataUtil().getId(entityName, entity));
    }

    protected boolean _exists(String entityName, Serializable id) {
        if (entityName == null)
            throw new NullPointerException("EntityName is null.");
        if (id == null)
            return false;
        Query query = getSession().createQuery("select id from " + entityName + " where id = :id");
        query.setParameter("id", id);
        return query.list().size() == 1;
    }

    protected boolean[] _exists(String entityName, Serializable... ids) {
        if (entityName == null)
            throw new NullPointerException("EntityName is null.");

        boolean[] ret = new boolean[ids.length];

        // we can't use "id in (:ids)" because some databases do not support
        // this for compound ids.
        StringBuilder sb = new StringBuilder("select id from " + entityName + " where");
        boolean first = true;
        for (int i = 0; i < ids.length; i++) {
            if (first) {
                first = false;
                sb.append(" id = :id");
            } else {
                sb.append(" or id = :id");
            }
            sb.append(i);
        }

        Query query = getSession().createQuery(sb.toString());
        for (int i = 0; i < ids.length; i++) {
            query.setParameter("id" + i, ids[i]);
        }

        for (Serializable id : (List<Serializable>) query.list()) {
            for (int i = 0; i < ids.length; i++) {
                if (id.equals(ids[i])) {
                    ret[i] = true;
                    // don't break. the same id could be in the list twice.
                }
            }
        }

        return ret;
    }

    protected com.hutgin2.dao.search.Filter _getFilterFromExample(String entityName, Object example) {
        return searchProcessor.getFilterFromExample(entityName, example);
    }

    protected com.hutgin2.dao.search.Filter _getFilterFromExample(String entityName, Object example, ExampleOptions options) {
        return searchProcessor.getFilterFromExample(entityName, example, options);
    }

}
